package com.exampls.word.docx;

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.math.BigInteger;
import java.util.List;

import static com.exampls.word.constant.CommonConstant.OUTPUT_DESKTOP_PATH;

/**
 * @Author : LukeRen
 * @DateTime: 2021/11/26 9:55
 * @Description : 生成可打印表格
 * @Version : 1.0
 */
public class CreatTableCase {

    /**
     * 生成一行一列可打印表格表格
     * 生成可打印表格 document.xml 中必须有 tblGrid, 由一下代码生成
     *  table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(3*1440));
     *  tblWidth.setW(BigInteger.valueOf(1*1440));
     *
     *  note: OROC 表示 one row one column
     *
     * @param doc
     */
    public static void createTableOROCPrintable(XWPFDocument doc){
        // Create a new table with 1 rows and 1 columns
        int nRows = 1;
        int nCols = 1;
        XWPFTable table = doc.createTable(nRows, nCols);

        // Set the table style. If the style is not defined, the table style
        // will become "Normal".
        CTTblPr tblPr = table.getCTTbl().getTblPr();

        table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(3*1440));

        CTString styleStr = tblPr.addNewTblStyle();
        styleStr.setVal("StyledTable");

        // Get a list of the rows in the table
        List<XWPFTableRow> rows = table.getRows();

        XWPFTableRow row = rows.get(0);

        // get table row properties (trPr)
        CTTrPr trPr = row.getCtRow().addNewTrPr();
        // set row height; units = twentieth of a point, 360 = 0.25"
        CTHeight ht = trPr.addNewTrHeight();
        ht.setVal(BigInteger.valueOf(360));

        // get the cells in this row
        List<XWPFTableCell> cells = row.getTableCells();
        // add content to each cell
        XWPFTableCell cell = cells.get(0);
        //设置背景颜色, 方便查看图片位置
//        cell.setColor("ED2323");
        //set width for first column = 1 inches
        CTTblWidth tblWidth = cell.getCTTc().addNewTcPr().addNewTcW();
        tblWidth.setW(BigInteger.valueOf(1*1440));
        //STTblWidth.DXA is used to specify width in twentieths of a point.
        tblWidth.setType(STTblWidth.DXA);

        cell.addParagraph();

        // get 1st paragraph in cell's paragraph list
        XWPFParagraph para = cell.getParagraphs().get(0);
        // create a run to contain the content
        XWPFRun rh = para.createRun();
        // last column is 10pt Courier
        rh.setFontSize(14);
        para.setVerticalAlignment(TextAlignment.CENTER);
        para.setAlignment(ParagraphAlignment.CENTER);

        ADDImages.addImages(rh, OUTPUT_DESKTOP_PATH + "333.png");

        rh.addBreak();
        rh.setText("(1)");

        //移除单元格表格
        TableUtils.removeBorders(row.getCell(0));

    }
}
